<?php

namespace app\admin\controller\zixun;

use app\admin\controller\Controller;
use app\admin\model\article\Article as ArticleModel;
use app\admin\model\article\Category as CategoryModel;
use think\Session;
use think\Db;

/**
 * 房源控制器模型
 * Class Category
 * @package app\store\controller\content
 */
class Build extends Controller
{
    public function index(){
         $list=Db::name('yonghui_zixun')->order(['createTime' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
        return $this->fetch('index', compact('list'));
    }
    /**
     * 页面预览
     */
    public function info($id){
        $buildId=$id;
        if(empty($buildId)){
            return json(['msg'=>'楼盘id不能为空','code'=>'error','data'=>[]]);
        }
        //判断该房源状态
        $buildInfo=Db::name('yonghui_building')->where(['id'=>$buildId])->find();
        if(empty($buildInfo)){
            return json(['msg'=>'未获取到楼盘信息','code'=>'error','data'=>[]]);
        }
        if($buildInfo['status']==2){
            return json(['msg'=>'该楼盘已下架','code'=>'error','data'=>[]]);
        }
        //获取首页轮播，楼盘轮播，沙盘轮播，配套图片，售楼处图片
        $buildInfo['bannerids']=$this->getImageUrl(json_decode($buildInfo['bannerids'],'true'));
        $buildInfo['loupanimageids']=$this->getImageUrl(json_decode($buildInfo['loupanimageids'],'true'));
        $buildInfo['shapanimageids']=$this->getImageUrl(json_decode($buildInfo['shapanimageids'],'true'));
        $buildInfo['peitaoimageids']=$this->getImageUrl(json_decode($buildInfo['peitaoimageids'],'true'));
        $buildInfo['slimageids']=$this->getImageUrl(json_decode($buildInfo['slimageids'],'true'));
        $buildInfo['characteristic']=explode('@',$buildInfo['characteristic']);
        $buildInfo['qita']=explode('@',$buildInfo['qita']);
        //将楼盘详情用
        //$buildInfo['miaoshu']=htmlspecialchars_decode($buildInfo['miaoshu']);
        //$buildInfo['miaoshu']=str_replace("<img ", "<img style='width:100%;height:auto;'", $buildInfo['miaoshu']);
        //$buildInfo['buildingDetail']=htmlspecialchars_decode($buildInfo['buildingDetail']);
        //$buildInfo['buildingDetail']= str_replace("<img ", "<img style='width:100%;height:auto;'", $buildInfo['buildingDetail']);
        //获取与预览人信息
        $user=Db::name('yonghui_adminuser')->where(['id'=>Session::get('yoshop_adminuser')['user']['admin_user_id']])->field('name,phone,id')->find();
        $this->view->engine->layout(false);
        //var_dump($buildInfo);
        $buildInfo['userInfo']=$user;
        return $this->fetch('info', compact('buildInfo'));
    }
    /**
     * 添加楼盘动态
     */
    public function addevent(){
        $loupanid=input('get.id');
        $dynamic=Db::name('yonghui_building_dynamic')->where(['loupanid'=>$loupanid])->select()->toArray();
        if($dynamic){
            foreach($dynamic as $k=>$v){
                $userName=Db::name('yonghui_adminuser')->where(['id'=>$v['userId']])->value('name');
                $dynamic[$k]['userName']=$userName;
                $dynamic[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
            }
        }
        $men['id']=$loupanid;
        return $this->fetch('addevent',compact('dynamic','men'));
    }
    public function addevents(){
        $data['content']=input('post.val');
        $data['title']='';
        $data['userId']=Session::get('yoshop_adminuser')['user']['admin_user_id'];
        $data['createTime']=time();
        $data['updateTime']=0;
        $data['status']=1;
        $data['loupanid']=input('post.loupanId');
        $insert=Db::name('yonghui_building_dynamic')->insertGetId($data);
        if($insert){
            return ['code'=>'success'];
        }
        return ['code'=>'error'];
    }
    /**
     * 获取图片链接
     */
    private function getImageUrl($ids){
        $imageInfos=Db::name('upload_file')->where('file_id','in',$ids)->select();
        $arr=[];
        if($imageInfos){
            foreach($imageInfos as $k=>$v){
                $arr[]=$v['file_url'].'/'.$v['file_name'];
            }
        }
        return $arr;
    }
    /**
     * 添加房源
     */
    public function add(){
        if(empty($this->postData('goods')['name'])){
            return $this->fetch('add');
        }
        //新增资讯
        $data=$this->postData('goods');
        $data['createTime']=time();
        $insert=Db::name('yonghui_zixun')->insertGetId($data);
        if($insert){
            return $this->success('添加成功', 'index');
        }
        return $this->renderError('添加失败');
    }

    /**
     * 更新资讯信息
     */
    public function edit($id){
        //资讯详情
        if (empty($this->postData('goods')['name'])){
            $model=Db::name('yonghui_zixun')->where(['id'=>$id])->find();
            return $this->fetch('edit', compact('model'));
        }
        //更新资讯信息
        $data=$this->postData('goods');
        $insert=Db::name('yonghui_zixun')->where(['id'=>$id])->update($data);
        if ($insert) {
            return $this->success('修改成功', 'zixun.build/index');
        }
        return $this->renderError('更新失败');
    }

    /**
     * 下架房源
     */
    public function delete($id){
        //房源详情
        $model = ArticleModel::detail($id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->success('删除成功','index');
    }

    /**
     * 上架房源
     */
    public function up($id){
        //房源详情
        $model = ArticleModel::detail($id);
        if (!$model->up()) {
            return $this->renderError($model->getError() ?: '上架失败');
        }
        return $this->success('上架成功','index');
    }

    /**
     * 一键同步环球商旅楼盘信息
     */
    public function asnc(){
        //查询环球商旅数据
        $huanqiuInfo=Db::name('yonghui_building')->where(['companyId'=>3])->select()->toArray();
        //查询当前公司楼盘数据
        $thisInfo=Db::name('yonghui_building')->where(['companyId'=>7])->select()->toArray();
        //将当前公司不存在的数据导入，存在的(根据用户名称进行判定)数据进行更新处理
        $newArray=[];
        if(!$thisInfo){
            //完全不存在，直接导入
            foreach ($huanqiuInfo as $k=>$v){
                $newArray[$k]['name']=$v['name'];
                $newArray[$k]['bannerids']=$v['bannerids'];
                $newArray[$k]['province']=$v['province'];
                $newArray[$k]['city']=$v['city'];
                $newArray[$k]['country']=$v['country'];
                $newArray[$k]['detail']=$v['detail'];
                $newArray[$k]['avgprice']=$v['avgprice'];
                $newArray[$k]['characteristic']=$v['characteristic'];
                $newArray[$k]['property']=$v['property'];
                $newArray[$k]['developer']=$v['developer'];
                $newArray[$k]['propertyName']=$v['propertyName'];
                $newArray[$k]['propertyPrice']=$v['propertyPrice'];
                $newArray[$k]['parking']=$v['parking'];
                $newArray[$k]['measure']=$v['measure'];
                $newArray[$k]['architecture']=$v['architecture'];
                $newArray[$k]['properType']=$v['properType'];
                $newArray[$k]['minmoney']=$v['minmoney'];
                $newArray[$k]['bayArea']=$v['bayArea'];
                $newArray[$k]['deliveryTime']=$v['deliveryTime'];
                $newArray[$k]['circle']=$v['circle'];
                $newArray[$k]['periphery']=$v['periphery'];
                $newArray[$k]['count']=$v['count'];
                $newArray[$k]['sellStatus']=$v['sellStatus'];
                $newArray[$k]['lczk']=$v['lczk'];
                $newArray[$k]['projectGo']=$v['projectGo'];
                $newArray[$k]['istygl']=$v['istygl'];
                $newArray[$k]['yszh']=$v['yszh'];
                $newArray[$k]['ysfzsj']=$v['ysfzsj'];
                $newArray[$k]['kaiPaiTime']=$v['kaiPaiTime'];
                $newArray[$k]['loupanimageids']=$v['loupanimageids'];
                $newArray[$k]['shapanimageids']=$v['shapanimageids'];
                $newArray[$k]['peitaoimageids']=$v['peitaoimageids'];
                $newArray[$k]['companyId']=Session::get('yoshop_adminuser')['user']['company_id'];
                $newArray[$k]['slimageids']=$v['slimageids'];
                $newArray[$k]['shoulouAdd']=$v['shoulouAdd'];
                $newArray[$k]['createTime']=$v['createTime'];
                $newArray[$k]['updateTime']=$v['updateTime'];
                $newArray[$k]['buildingDetail']=$v['buildingDetail'];
                $newArray[$k]['bankuaiId']=$v['bankuaiId'];
                $newArray[$k]['projectId']=$v['projectId'];
                $newArray[$k]['miaoshu']=$v['miaoshu'];
                $newArray[$k]['jingdu']=$v['jingdu'];
                $newArray[$k]['weidu']=$v['weidu'];
                $newArray[$k]['xiaoshouticheng']=$v['xiaoshouticheng'];
                $newArray[$k]['chewei']=$v['chewei'];
                $newArray[$k]['jiaotong']=$v['jiaotong'];
                $newArray[$k]['yiliao']=$v['yiliao'];
                $newArray[$k]['shangcheng']=$v['shangcheng'];
                $newArray[$k]['jiaoyu']=$v['jiaoyu'];
                $newArray[$k]['shenghuo']=$v['shenghuo'];
                $newArray[$k]['bili']=$v['bili'];
                $newArray[$k]['pinpai']=$v['pinpai'];
                $newArray[$k]['status']=$v['status'];
                $newArray[$k]['qita']=$v['qita'];
            }
            //写入楼盘表
            $insert=Db::name('yonghui_building')->insertAll($newArray);
            if($insert){
                return $this->success('同步成功','index');
            }
        }else{
            //将有的数据更新，没有的数据进行插入
            $names=[];
            foreach ($thisInfo as $k=>$v){
                $names[]=$v['name'];
            }
            $newArray=[];
            foreach ($huanqiuInfo as $k1=>$v1){
                if(in_array($v1['name'],$names)){
                    //更新
                    $info=Db::name('yonghui_building')->where(['name'=>$v1['name'],'companyId'=>3])->find();
                    unset($info['id']);
                    $info['companyId']=Session::get('yoshop_adminuser')['user']['company_id'];
                    $update=Db::name('yonghui_building')->where(['name'=>$v1['name'],'companyId'=>Session::get('yoshop_adminuser')['user']['company_id']])->update($info);
                }else{
                    unset($v1['id']);
                    $newArray[]=$v1;
                    $newArray['companyId']=Session::get('yoshop_adminuser')['user']['company_id'];
                    $ins=Db::name('yonghui_building')->insert($newArray);
                }
            }
            return $this->success('同步更新成功','index');
        }
    }
}
